<template>


  <div class="app-container">
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
    <el-tab-pane label="待处理" name="1"> </el-tab-pane>
    <el-tab-pane label="已处理" name="10"> </el-tab-pane>
  </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="订单编号:" prop="queryOrederId">
        <el-input
          v-model="queryParams.queryOrederId"
          placeholder="根据订单编号搜索"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
 
      <el-form-item label="购买人qq号:" prop="queryBuyQQ">
        <el-input
          v-model="queryParams.queryBuyQQ"
          placeholder="根据qq号搜索"
          clearable
          style="width: 120px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

 
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
 

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="证明图片" align="center" prop="src" width="400">
        <template #default="scope">
          <div class="invitation-image-list">
            <div v-for="(item, index) in scope.row.imagesList" :key="index">
              <el-image
                :key="index"
                style="width: 100px; height: 100px"
                :src="uploadShowUrl + item"
                :preview-teleported="true"
                :preview-src-list="[uploadShowUrl + item]"
                fit="contain"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" 
      align="center" prop="orderId" width="150" />
      <el-table-column
        label="申请人QQ"
        align="center"
        prop="buyQQ"
        width="150"
        :show-overflow-tooltip="true"
      >
      </el-table-column>

    <el-table-column
        label="类型"
        align="center"
        prop="errorType"
        width="120"
      >
        <template #default="scope">
          <dict-tag :options="errorTypeList" :value="scope.row.errorType" />
        </template>
      </el-table-column>
    <el-table-column
        label="申请内容"
        align="center"
        prop="content"
        width="320"
       
      />
      <el-table-column
        label="申请日期"
        align="center"
        prop="createdAt"
        width="100"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
         <el-table-column
        label="修改日期"
        align="center"
        prop="updatedAt"
        width="100"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
       
      <el-table-column
        label="状态"
        align="center"
        prop="errorStatus"
        width="150"
      >
        <template #default="scope">
          <dict-tag :options="errorStatusList" :value="scope.row.errorStatus" />
        </template>
      </el-table-column>

      <el-table-column
        label="订单备注"
        align="center"
        prop="remarks"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="操作"
        align="center"
        width="200"
        :fixed="desk"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleApprove(scope.row)"
            
              >审核</el-button
            >
        <el-button
            v-if="scope.row.errorStatus>2"
            v-hasPermi="['del']" 
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
  
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
       <!-- 添加或修改公告对话框 -->
       <el-dialog :title="title" v-model="open1" width="780px" append-to-body>
        <el-form ref="noticeRef1" :model="form1" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="审核意见" prop="approve">
                <el-radio-group v-model="form1.approve">
                  <el-radio
                    v-for="dict in approveList"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form1.approve == 10">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入备注"
                  v-model="form1.remarks"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="debouncedFn1">确 定</el-button>
            <el-button @click="cancel1">取 消</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup name="Order">
import {
 
  updateOrderZhuan,
 
} from "@/api/business/order";

import {
  listErrorOrder,
  updateErrorOrder,
  approveErrorOrder,
  delErrorOrder,
  
} from "@/api/business/orderError";


 

 
import { listGoods  } from "@/api/business/goods";
import { listUser , listAllUser} from "@/api/business/user";
 
import { useDebounceFn } from "@vueuse/core";
import useDesk from "@/hooks/useDesk";
import { errorStatusEnums ,orderStatusEnums ,errorTypeEnums  } from "@/utils/enums"
 

const { desk } = useDesk();
const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFile/file";
const uploadUrl1 =
  import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFileEdit/file";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;

const imgSrc = ref("");
const pageList = ref([]);
const open = ref(false);
const open1 = ref(false);


const dialogOpen1 = ref(false); // 导出表格
const dialogOpen2 = ref(false); // 导入表格
 
const activeName =ref('1')
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const painterList = ref([]); // 画师下拉框
const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);
// 是否赞助
const statusComList = ref([
  { label: "否", value: 1 },
  { label: "是", value: 2 },
]);
const approveList = ref([
    { label: "处理完成", value: 1 },
    { label: "待处理,去备注", value: 10 },
  ]);
 
const loadingGoods = ref(false);

const optionsPainterList = ref([]);  
const optionsGoodsList = ref([]);  

const optionsUser = ref([]); //  用户搜索
const loadingUser = ref(false);
 
const loadingSubmit = ref(false);
const loadingBtn = ref(false);
const fileList = ref([]);

const dateRange = ref([]);
 
const takeoutStatusList = ref([
  {
    label: "可以转让",
    value: "1",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "禁止转让：商品禁止转让",
    value: "2",
    elTagClass: "",
    elTagType: "danger",
  },
  {
    label: "禁止转让：订单已经被转让过了",
    value: "3",
    elTagClass: "",
    elTagType: "danger",
  },
  {
    label: "禁止转让：购买日期不在3个月至1年之内",
    value: "4",
    elTagClass: "",
    elTagType: "danger",
  },
]);
// 赞助状态
const stutasList = ref([
 // 1标准单  2转让单  3待赠单  4已赠单'
  {
    label: "标准单",
    value: 1,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "转让单",
    value: 2,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "待赠单",
    value: 3,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "已赠单",
    value: 4,
    elTagClass: "",
    elTagType: "success",
  },
]);
const data = reactive({
  errorTypeList:errorTypeEnums,
  statusList:orderStatusEnums,
  errorStatusList:errorStatusEnums,
  form: {},
  form1: {},
  dialogForm1: {
    goodsId: undefined,
    beginTime: undefined,
    end: undefined,
    painterId: undefined,
  }, // 导出弹出框选择
  dialogForm2: {
    goodsId: undefined,
  }, // 导出弹出框选择
 
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    errorStatus:1,
    queryOrederId: undefined,
    queryGoodsId: undefined,
    queryPainterQQ: undefined,
    queryUserName: undefined,
    queryTransferQQ: undefined,
    queryStartEndTime: undefined,
  },
  rules: {
    goodsId: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    buyerQQ: [
      { required: true, message: "购买用户QQ不能为空", trigger: "change" },
    ],
    type: [
      { required: true, message: "订单类型不能为空", trigger: "change" },
    ],
 
  },
});

const { queryParams, form, dialogForm1,
  errorTypeList,
  typeList,
  form1,
  errorStatusList,
  statusList,
  dialogForm2,  rules } =
  toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listErrorOrder(proxy.addDateRangeZL(queryParams.value, dateRange.value)).then(
    (response) => {
      pageList.value = response.data.rows.map((item) => {
        let imagesList = [];
        if (item.src) {
          imagesList = item.src.split(",");
        }
        return {
          ...item,
          imagesList: imagesList,
        };
      });
      total.value = response.data.count;
      loading.value = false;
    }
  );
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 取消按钮 */
function cancel1() {
  open1.value = false;
  reset1();
}
/** 新增表单重置 */
function reset1() {
  form1.value = {

  };

  proxy.resetForm("noticeRef1");
}

/** 新增表单重置 */
function reset() {
  form.value = {

  };
  data.rules = {
    goodsId: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    buyerQQ: [
      { required: true, message: "购买用户QQ不能为空", trigger: "change" },
    ],
    type: [
      { required: true, message: "订单类型不能为空", trigger: "change" },
    ],
  };
  proxy.resetForm("noticeRef");
}

 

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
 
/** 取消按钮 */
function dialogCancel1() {
  dialogOpen1.value = false;
  dialogReset1();
}
/** 取消按钮 */
function dialogCancel2() {
  dialogOpen2.value = false;
  dialogReset2();
}
 
function handleExport() {
  dialogReset1();
  dialogOpen1.value = true;
  title.value = "导出表格";
}
 

/** 表单重置 */
function dialogReset1() {
  proxy.resetForm("orderRef1");
}

/** 表单重置 */
function dialogReset2() {
  proxy.resetForm("orderRef2");
  fileList.value = [];
}

 
 

/**修改按钮操作 */
function handleUpdate(row) {
  reset();

  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      ...arr[0],
      name: arr[0].goodsName,
    };
  } else {
    form.value = {
      ...row
    };
 
    optionsGoodsList.value = [
      {
        label: row.goodsName,
        value: row.goodsId,
      },
    ];
 
  }
  title.value = "修改";
  open.value = true;
}

// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true;
      if (form.value.id != undefined) {
        if (form.value.takeoutStatusOld == 1 && form.value.takeoutStatus == 2) {
          updateOrderZhuan(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              loadingSubmit.value = false;
              open.value = false;

              getList();
            })
            .catch(() => {
              loadingSubmit.value = false;
            });
        } else {
          updateErrorOrder(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              loadingSubmit.value = false;
              open.value = false;

              getList();
            })
            .catch(() => {
              loadingSubmit.value = false;
            });
        }
      } else {
  
   
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }
  let arrList = pageList.value.filter((item) => {
    return;
  });
  proxy.$modal
    .confirm('是否确认删除编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return delErrorOrder({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
 
 
 

  /**审核按钮操作 */
  function handleApprove(row) {
 
    form1.value.id = row.id;
    open1.value = true;
    title.value = "审批";
  }
  // 防抖操作
  const debouncedFn1 = useDebounceFn(
    () => {
      submitForm1();
    },
    1000,
    { maxWait: 3000 }
  );

  /** 提交按钮 */
function submitForm1() {
  if(!form1.value.id){
    proxy.$modal.msgSuccess("错误");
  }
  proxy.$refs["noticeRef1"].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true;
      let sendData={}
      if(form1.value.approve == 1 ){
        sendData={
          errorStatus:10,
          ids:[form1.value.id],
          
        }
      }else if (form1.value.approve == 10 ){
        
        sendData={
            errorStatus: 1,
            ids:[form1.value.id],
            remarks: form1.value.remarks
        }
      }
      approveErrorOrder(sendData)
            .then((response) => {
              proxy.$modal.msgSuccess("操作成功");
              loadingSubmit.value = false;
              open1.value = false;
              getList();
            })
            .catch(() => {
              loadingSubmit.value = false;
            });

    }
  });
}

const handleTabClick=(tab ,event )=>{
 
 
  dateRange.value = [];
  proxy.resetForm("queryRef");

 
     data.queryParams.errorStatus = tab.props.name
 

    handleQuery();
}
watch(
  () => data.dialogForm1.painterId,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      goodsHttp(); // 重新搜索
      data.dialogForm1.goodsId = undefined;
    }
  },
  { deep: true }
);

getList();
 
 
</script>
<style lang="scss" scoped>
.goods-name {
  color: rgb(0, 119, 255);
  cursor: pointer;
}
.green {
  color: #2eacf5;
}
.red {
  color: red;
}
</style>
